package org.fuys.etp.core.metrics.impl.trend;


import org.fuys.etp.core.metrics.EtpMetricsHandler;
import org.fuys.etp.core.metrics.impl.trend.type.StageJudgeTypeProcessor;
import org.fuys.etp.core.model.type.EtpTaskTrendTypeEnum;
import org.fuys.etp.core.model.vo.TpConfigVO;
import org.fuys.etp.core.model.vo.TpFixedConfigVO;
import org.fuys.etp.core.model.vo.TpStatusVO;
import org.fuys.etp.core.pool.EtpThreadPoolExecutor;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @projectName: fuys-etp-final
 * @package: org.fuys.etp.core.metrics.impl.trend
 * @className: StageSwitchTrendHandler
 * @author: WangJing
 * @description: 阶段性线程池趋势处理器
 * @date: 2025/2/18 22:30
 * @version: 1.0
 */
@Component("stageSwitchTrendHandler")
public class StageSwitchTrendHandler implements EtpMetricsHandler {


    Map<String, StageJudgeTypeProcessor> judgeProcessorMap;

    @Autowired
    public StageSwitchTrendHandler(ListableBeanFactory beanFactory){
        judgeProcessorMap = beanFactory.getBeansOfType(StageJudgeTypeProcessor.class);
    }

    @Override
    public void metricsCollect(ThreadPoolExecutor executor, TpStatusVO result) {
        Integer taskTrend = EtpTaskTrendTypeEnum.UNABLE.getType();
        if(executor instanceof EtpThreadPoolExecutor){
            EtpThreadPoolExecutor fixedTp = (EtpThreadPoolExecutor) executor;
            final TpConfigVO curConfig = fixedTp.getActualConfig();
            final TpFixedConfigVO fixedConfig = curConfig.getFixedConfig();
            final StageJudgeTypeProcessor expansionProcessor = judgeProcessorMap
                    .get(fixedConfig.getExpansionNumType().toString());
            if(expansionProcessor == null){
                throw new IllegalArgumentException("Fuys etp:没有找到阈值检测器:"+fixedConfig.getExpansionNumType().toString()
                        +" 请检查配置");
            }
            final Integer exJudge = expansionProcessor.judge(true,
                    fixedConfig.getExpansionCompareType().toString(), executor, curConfig);
            if(EtpTaskTrendTypeEnum.INCREASE.getType().equals(exJudge)){
                taskTrend = exJudge;
            }else{
                final StageJudgeTypeProcessor scaleInProcessor = judgeProcessorMap
                        .get(fixedConfig.getScaleNumType().toString());
                if(scaleInProcessor == null){
                    throw new IllegalArgumentException("Fuys etp:没有找到阈值检测器:"+fixedConfig.getExpansionNumType().toString()
                            +" 请检查配置");
                }
                taskTrend = scaleInProcessor.judge(false,
                        fixedConfig.getScaleCompareType().toString(), executor, curConfig);
            }
        }
        result.setTaskTrend(taskTrend);
    }
}
